<template>
  <!-- 出库模板  唐美莉 -->
  <div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="left"
      class="durg_form"
      @submit.native.prevent="onSubmit"
    >
      <el-row>
        <el-col :span="24">
          <label class="durg_title">编辑出库</label>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4" prop="putInStorageDate">
          <el-form-item>
            <el-date-picker
              v-model="form.putInStorageDate"
              type="date"
              :editable="true"
              value-format="yyyy-MM-dd"
              placeholder="出库日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="outWay">
            <el-select v-model="form.outWay" value-key="id" placeholder="出库方式">
              <el-option v-for="item in wayList" :key="item.id" :label="item.desc" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item  prop="receiveDeptId">
            <el-select filterable @change="getDoctor" placeholder="领用科室" v-model="form.receiveDeptId">
              <el-option
                v-for="(item,index) in deptList"
                :key="index"
                :value="item.deptId"
                :label="item.deptName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="receiveUserId">
            <el-select filterable placeholder="领用人员" v-model="form.receiveUserId">
              <el-option
                v-for="(item,index) in doctorList"
                :key="index"
                :value="item.memberId"
                :label="item.trueName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-input placeholder="备注" v-model="form.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <edit
        v-model="dialogEdit"
        v-if="dialogEdit"
        :totalMoney="form.totalMoney"
        :itemList="medicalStockItem"
        @getTotal="getTotal"
      ></edit>
      <el-row>
        <el-col :span="24">
          <el-button @click="addItem()" type="text">
            <i class="el-icon-plus"></i>
            添加
          </el-button>
        </el-col>
      </el-row>
      <el-button v-show="false" :loading="btnLoading" native-type="submit">提交</el-button>
    </el-form>
    <br />
    <span slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="onSubmit(1)">保 存</el-button>
      <el-button type="promary" @click="onSubmit(2)">保 存 并 审 核</el-button>
      <el-button @click="onClose">取消</el-button>
    </span>
  </div>
</template>
<script>
import Valid from "@/_js/validate.js";
export default {
  data() {
    return {
      btnLoading: false,
      form: {
        id: "",
        // hpId: "",
        type:2,
        source:2,//1药品2物资
         receiveDeptId: "",//领用科室
        receiveUserId:'',//领用人
        receiveId: "",
        stockCode: "",
        outWay: "",
        sendGoodsDate: "",
        putInStorageDate: "",
        memberId: "",
        saveType: 1,
        remark: "",
        supplierId: "",
        status: 0,
        totalMoney: 0
      },
      medicalStockItem: [
        {
          source: 2, //来源
          durg: "",
          batchId:'',//批次
          itemId:'',
          sourceName: "", //来源物品名
          sourceId: "", //来源id
          lotNumber: "", //批号
          effectiveTime: "", //有效期
          outQuantity: 0, //增减制剂数量
          outQuantityUnit: "", //增减包装单位
          purchasePrice: 0, //进价
          purchaseMoney: 0, //进价金额
          remark: "", //描述
          retailPrice: "", //零售价
          costPrice: "", //成本价
          show: false,
          psc: "", //库存数量
          acceptanceConclusion: 1 //验收结论
        }
      ],
      deptList: [],
      doctorList:[],
      supplierList: [],
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() > Date.now();
        }
      },
      wayList: [],
      rules: {
        putInStorageDate: [{ required: true, message: "此项必填", trigger: "change" }],
        outWay: [{ required: true, message: "此项必填", trigger: "change" }],
        receiveDeptId: [
          { required: true, message: "此项必填", trigger: "change" }
        ],
        receiveUserId: [
          { required: true, message: "此项必填", trigger: "change" }
        ]
      },
      durg_id: 0,
      dialogEdit: true,
      curItem: {}
    };
  },
  created(){
    this.getDoctor('')
  },
  mounted() {
    let th = this;
    th.verifyUrlAttack(th.$route.query).then(() => {
      th.durg_id = th.jieMi(th.$route.query.id);
      
      th.getBasicData();
      th.onOpen();
    });
  },
  methods: {
    onSubmit(type) {
      let th = this;
      let j = {
       medicalStockOutPutRequest: "",
        medicalStockOutPutDetailRequests: ""
      };
      th.form.memberId = th.jieMi(th.adminUser.memberId);
      j.saveType = type;
      let add = function() {
        th.btnLoading = true;
        th.$api.addPutStorge(j).then(res => {
          if (res.executed) {
            th.$message.success("保存成功");
            th.$emit("success");
            th.onClose();
          } else {
            th.$message.error(res.message);
          }
        });
        th.btnLoading = false;
      };
      let update = function() {
        th.btnLoading = true;
        th.$api.editPutStorge(j).then(res => {
          if (res.executed) {
            th.$message.success("保存成功");
            //获取对应的科室名称
            th.$emit("success");
            th.onClose();
          } else {
            th.$message.error(res.message);
          }
        });
        th.btnLoading = false;
      };
      th.$refs["form"].validate(v => {
        if (v) {
          // th.form.hpId = th.adminUser.hpId;
          th.form.memberId = th.adminUser.memberId;
          let list = th.medicalStockItem;
          let isB = true;
          // for (let i = 0; i < list.length; i++) {
          //   if (list[i].count < 1) {
          //     th.$message.error("数量不能小于0！");
          //     isB = false;
          //     break;
          //   }
          //   if (list[i].effectiveTime == "") {
          //     th.$message.error("有效期不能为空！");
          //     isB = false;
          //     break;
          //   }
          // }
          for (let i = 0; i < list.length; i++) {
            if (list[i].outQuantity < 1) {
              th.$message.error("数量不能小于0！");
              isB = false;
              break;
            }
            if (list[i].outQuantityUnit == list[i].residueNumUnit) {
              if (list[i].outQuantity > list[i].residueNum) {
                th.$message.error("出库数量不能超过库存数量");
                isB = false;
                break;
              }
            } else {
              if (list[i].outQuantity > list[i].residueNumSubsection) {
                th.$message.error("出库数量不能超过库存数量");
                isB = false;
                break;
              }
            }
          }
          if (isB == false) {
            return false;
          }
          j.medicalStockOutPutRequest = th.form;
          let itemList=th.medicalStockItem
          itemList.map((it)=>{
            delete it.durg;
            delete it.unitList;
          })
          j.medicalStockOutPutDetailRequests =itemList;
          if (th.durg_id != 0) {
            update();
          } else {
            add();
          }
        }
      });
    },
    onOpen() {
      let th = this;
      th.$nextTick(function() {
        if (th.durg_id != 0) {
          th.$api.getPutDetailV2({ outPutId: th.durg_id }).then(res => {
            if (res.executed) {
              th.form = Object.assign(th.form, res.data.medicalStockOutPutDisplayVO);
              let list = [];
              let sum = 0;
              // let d = res.data.medicalStockOutPutDetailDisplayVOS;
              // for (let i = 0; i < d.length; i++) {
              //   let arr = { show: true };
              //   arr = Object.assign(arr, d[i]);
              //   sum += Number(d[i].purchaseMoney);
              //   list.push(arr);
              // }
              if (th.form.receiveDeptId) {
                th.getDoctor(th.form.receiveDeptId);
              }
              let d = res.data.medicalStockOutPutDetailDisplayVOS;
              d.map(it=>{
                it.show=true;
                it.sourceName=it.goodsName;
                it.sourceId=it.goodsId;
                let unit=[]
                unit.push(it.outQuantityUnit)
                it.unitList=unit;
                sum += Number(it.purchaseMoney);
              })
              th.form.totalMoney = sum;
              th.medicalStockItem = d;
            }
          });
        }
      });
    },
    onClose() {
      let th = this;
      // th.$refs["form"].resetFields();
      th.$router.push({
        path: "/page/suppliesIndex",
        query: th.getUrlToken({id:th.jiaMi(1)})
      });
    },
    //获取通用配置
    getBasicData() {
      let th = this;
      th.getCommonConfigByKey("出库方式").then(res => {
        th.wayList = res;
      });
      //科室
       th.$api.getDepartmentPageList({ pageNum: "1", pageSize: "1000",hpId:th.adminUser.hpId }).then(res => {
          if (res.executed) {
            th.deptList = res.dataBody.list;
          }
      });
    },
    getDoctor(item){
      let th=this;
        th.$api.getDoctorPageList({ pageNum: "1", pageSize: "1000",deptId:item,hpId:th.adminUser.hpId }).then(res => {
          if (res.executed) {
            th.doctorList = res.dataBody.list;
          }
        });
    },
    addItem() {
      let th = this;
      let json = {
        source: 2, //来源
        durg: "",
        sourceName: "", //来源物品名
        sourceId: "", //来源id
        lotNumber: "", //批号
        effectiveTime: "", //有效期
        count: 0, //增减制剂数量
        packUnit: "", //增减包装单位
        purchasePrice: 0, //进价
        purchaseMoney: 0, //进价金额
        remark: "", //描述
        retailPrice: "", //零售价
        costPrice: "", //成本价
        show: false,
        psc: "",
        acceptanceConclusion: 1 //验收结论
      };
      th.medicalStockItem.push(json);
    },
    getTotal(item) {
      let th = this;
      th.form.totalMoney = item;
    }
  },
  components: {
    edit: () => import("../_childcom/editStorage")
  }
};
</script>
<style lang="scss" scoped>
.durg_title {
  display: inline-block;
  width: 100%;
  font-size: 16px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}
.durg_form {
  .el-input,
  .el-select {
    width: 90%;
  }
  .el-form-item__label {
    padding-bottom: 0;
  }
  .one_dose_select {
    width: 30%;
    position: absolute;
    right: 28px;
  }
}
</style>
